package org.example.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.context.SecurityContextHolder;
import org.example.domain.system.constant.SecurityConstant;
import org.example.domain.system.model.LoginUser;
import org.example.utils.JwtUtils;
import org.example.utils.SecurityUtil;
import org.example.utils.ServletUtils;
import org.example.utils.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        SecurityContextHolder.setUserId(Long.getLong(ServletUtils.getHeader(request, SecurityConstant.SECURITY_USER_ID)));
        SecurityContextHolder.setUserName(ServletUtils.getHeader(request, SecurityConstant.SECURITY_USER_NAME));

        String token = SecurityUtil.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            LoginUser loginUser = JwtUtils.getLoginUser(token);
            if (loginUser != null) {
                SecurityContextHolder.set(SecurityConstant.SECURITY_LOGIN_USER, loginUser);
            }
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SecurityContextHolder.remove();
    }
}
